package com.ruding.disruptor.init;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import org.apache.tomcat.jni.Lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lmax.disruptor.WorkHandler;
import com.ruding.disruptor.config.ReportStatus;
import com.ruding.disruptor.mapper.EvidenceRecordMapper;
import com.ruding.disruptor.model.EvidenceRecord;
import com.ruding.disruptor.service.FilesServiceImpl;
import com.ruding.disruptor.utils.FileUtils;
import com.ruding.disruptor.utils.MapperProxy;
import com.ruding.disruptor.utils.http.DataSender;
@Service
public class SeriesDataEventHandler implements WorkHandler<SeriesDataEvent> {

    private Logger logger = LoggerFactory.getLogger(SeriesDataEventHandler.class);

//    @Autowired
//    private DeviceInfoService deviceInfoService;
    @Autowired
    SeriesDataEventQueueHelper queueHelper;
    
    @Autowired
    FilesServiceImpl filesServiceImpl;
    
	EvidenceRecordMapper mapper = MapperProxy.getMapper(EvidenceRecordMapper.class);

//    @Override
    public void onEvent(SeriesDataEvent event)  {
        if (event.getValue() == null || StringUtils.isEmpty(event.getValue().getType())) {
            logger.warn("receiver series data is empty!");
        }
        if(event.getValue().getType().equals("scan")){
        	logger.info(JSON.toJSONString(event));
        	scanFileList((String)event.getValue().getData(), event.getValue().getBatchId());
        }
    }
    
    
    public void scanFileList(String strPath,String sendUrl){
		File dir = new File(strPath);
		File[] files = dir.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) { // 判断是文件还是文件夹
					SeriesData<String> data = new SeriesData<>("scan", files[i].getAbsolutePath(), 1, sendUrl);
					queueHelper.tryPublishEvent(data);
//					scanFileList(files[i].getAbsolutePath(),sendUrl); // 获取文件绝对路径
				} else if (files[i].isFile() && files[i].getAbsolutePath().endsWith(".pdf")) { // 判断文件名是否以.avi结尾
					logger.info("处理目录："+files[i].getAbsolutePath());
					scanFileAndSend(files[i],sendUrl);
				} else {
					continue;
				}
			}
		}
	}

	/**
	 * 扫描并发送文件信息
	 * @param dir
	 * @param filter
	 */
	public void scanFileAndSend(File file,String url) {
		String filePath = file.getAbsolutePath();
		long lastModified = FileUtils.getFileMaxTime(file);
		EvidenceRecord record = mapper.getEvidenceRecord(filePath);
		List<String> filePaths = Arrays.asList(filePath);
		if(record != null&&record.isReported()) {
			return;
		}
		filesServiceImpl.scanFileAndSend(record,lastModified,filePaths,url);
	}

}
